import 'package:flutter/foundation.dart';
import 'package:async/async.dart';

/// 安全的 ChangeNotifier 基类，自动处理生命周期和异步取消
abstract class SafeChangeNotifier extends ChangeNotifier {
  bool _disposed = false;
  final Set<CancelableOperation> _operations = {};

  /// 检查是否已释放，已释放则抛异常（debug 模式）
  void _checkDisposed() {
    assert(!_disposed, '${runtimeType}已释放，不能再使用');
  }

  /// 安全通知：仅在未释放时通知
  void safeNotify() {
    if (!_disposed && hasListeners) {
      notifyListeners();
    }
  }

  /// 包装异步任务，自动在释放时取消
  Future<T> wrapAsync<T>(Future<T> Function() task) async {
    _checkDisposed();
    final operation = CancelableOperation.fromFuture(task());
    _operations.add(operation);
    try {
      return await operation.value;
    } on CanceledError {
      // 任务被取消时忽略错误
      return Future.value(null as T);
    } finally {
      _operations.remove(operation);
    }
  }

  @override
  void dispose() {
    if (_disposed) return;
    _disposed = true;
    // 取消所有未完成的异步任务
    for (final op in _operations) {
      op.cancel();
    }
    _operations.clear();
    super.dispose();
  }
}
